package com.lemon.cloud.springdoc;

import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.*;

import java.util.Optional;

/**
 * 配置springdoc
 */
@Configuration
@Profile(value = {"dev","test"})
@Import(SpringDocProperties.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class SpringMvcDocConfiguration {

    @Autowired
    private SpringDocProperties springDocProperties;

    @Bean
    public OpenAPI openAPI() {
        SpringDocProperties.ApiInfo apiInfo = Optional.ofNullable(springDocProperties.getApiInfo()).orElse(new SpringDocProperties.ApiInfo());
        return new OpenAPI()
                .info(apiInfo(apiInfo))
                .externalDocs(new ExternalDocumentation()
                        .description(apiInfo.description)
                        .url("https://springdoc.org/v2"));
    }

    private Info apiInfo(SpringDocProperties.ApiInfo apiInfo) {
        SpringDocProperties.Author author = Optional.ofNullable(springDocProperties.getAuthor()).orElse(new SpringDocProperties.Author());
        return new Info()
                .title(apiInfo.title)
                .description(apiInfo.getDescription())
                .version(apiInfo.getVersion())
                .contact(new Contact()
                        .name(author.getName())
                        .url(author.getUrl())
                        .email(author.getEmail())
                )
                .termsOfService(apiInfo.getTermsOfServiceUrl())
                .license(new License()
                        .name(apiInfo.getLicense())
                        .url(apiInfo.getLicenseUrl())
                );
    }
}
